package com.star.message.biz;

import com.google.common.collect.Sets;
import com.star.common.core.contract.enums.ResultCodeEnum;
import com.star.common.core.contract.exception.ServiceException;
import com.star.common.kit.contract.enums.language.RealLanguageTypeEnum;
import com.star.message.contract.param.UserEmailConfigParam;
import com.star.message.repository.model.UserEmailConfigBO;
import com.star.message.utils.EmailUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 邮件业务
 *
 * @author zhouhengzhe
 */
@Service
public class MessageEmailBizService {
    /**
     * 发送邮件
     *
     * @param tenantId     租户ID
     * @param languageCode 语言编码
     * @param email        邮箱
     * @param code         邮件模板code
     */
    public void sendEmail(String tenantId, String languageCode, String email, String code) {
        UserEmailConfigBO userEmailConfigBO = getUserEmailConfigOrDefault(tenantId, languageCode);
        EmailUtils emailUtils = new EmailUtils(userEmailConfigBO);
        //发送邮件
        emailUtils.sendSimpleMail(userEmailConfigBO.getPersonal(), Sets.newHashSet(email), null,
                userEmailConfigBO.getSubject(), emailUtils.buildEmailContent(userEmailConfigBO.getDomainUrl(),
                        userEmailConfigBO.getLogoUrl(), code, userEmailConfigBO.getContent())
        );
    }

    /**
     * 获取对应语言的邮件配置，如果不存在默认取EN英文的配置
     *
     * @param tenantId     租户ID
     * @param languageCode 语言编码
     * @return 邮件配置
     */
    private static UserEmailConfigBO getUserEmailConfigOrDefault(String tenantId, String languageCode) {
        //获取邮件配置
        List<UserEmailConfigBO> userEmailConfigBOList = UserEmailConfigParam
                .builder()
                .tenantId(tenantId)
                .languageCodeIn(Sets.newHashSet(languageCode, RealLanguageTypeEnum.EN.getCode()))
                .build().list();
        if (CollectionUtils.isEmpty(userEmailConfigBOList)) {
            //请配置默认模板
            throw new ServiceException(ResultCodeEnum.EMAIL_TEMPLATE_NOT_CONFIGURED);
        }
        //默认既有英文EN，也有当前要查询的语言
        if (userEmailConfigBOList.size() > 1) {
            return userEmailConfigBOList.stream()
                    .filter(userEmailConfigBO -> !RealLanguageTypeEnum.EN.getCode().equals(userEmailConfigBO.getLanguageCode()))
                    .findFirst()
                    //基本上不会出现下面报错，因为上面已经判断了
                    .orElseThrow(() -> new ServiceException(ResultCodeEnum.EMAIL_TEMPLATE_NOT_CONFIGURED));
        }
        //只有当前查询的语言，也可能当前查询的语言是英文EN
        return userEmailConfigBOList.get(0);
    }

}
